<script setup>
import { onMounted, ref, watch } from 'vue'
import { getArticleByIdApi, getChannelApi, postArticleApi } from '../../api'
import Quill from 'quill'
// import 'quill/dist/quill.snow.css'
import { toolbarOptions } from './toolbar.js'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

// 表单数据
const form = ref({
  title: '',
  channel_id: '',
  cover_type: 1,
})

// 表单验证规则
const formRules = ref({
  title: [{ required: true, message: '标题不能为空！', trigger: 'blur' }],
  channel_id: [{ required: true, message: '频道不能为空！', trigger: 'blur' }],
})

// 频道列表
const channelList = ref([])

// 图片列表
const files = ref([])
// 表单 ref
const formRef = ref(null)
// 路由(获取路径参数)
const route = useRoute()
// 路由(跳转路径)
const router = useRouter()

// 图片预览相关
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 单图切换时清空图片
watch(
  () => form.value.cover_type,
  () => {
    files.value = []
  }
)

// 获取频道列表
const getChannel = async () => {
  const res = await getChannelApi()
  channelList.value = res.data
}
// 获取文章详情
const getArticleById = async () => {
  const res = await getArticleByIdApi(route.query.id)
  form.value = { ...res.data }
  if (res.data.cover_images) {
    files.value = res.data.cover_images.map((url, index) => ({
      name: `image${index + 1}`, // 文件名可以自定义
      url: url,
      uid: -index - 1,
    }))
  }
  quill.root.innerHTML = res.data.content
}
// Quill编辑器
let quill
// 提交表单
const onSubmit = (status) => {
  formRef.value.validate(async (valid) => {
    // 验证表单不通过
    if (!valid) return
    // 图片数量有误
    if (form.value.cover_type !== files.value.length) {
      // 图片数量为0
      if (files.value.length === 0) {
        ElMessage.error('请上传图片！')
      } else {
        // 图片数量不足
        ElMessage.error('请上传所选数量的图片!')
      }
      return
    }
    // 准备数据
    const formData = new FormData()
    formData.append('title', form.value.title)
    formData.append('channel_id', form.value.channel_id)
    formData.append('cover_type', form.value.cover_type)
    formData.append('status', status)
    formData.append('content', quill.root.innerHTML)
    files.value.forEach((item) => {
      formData.append('cover_images', item.raw)
    })

    // 发送请求
    const res = await postArticleApi(formData)
    if (res.message === 'success') {
      ElMessage.success('发布成功')
      router.push('/content-manager')
    } else {
      ElMessage.error('发布失败')
    }
  })
}

// 处理图片预览
const onPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

onMounted(async () => {
  getChannel()
  if (route.query.id) {
    getArticleById()
  }

  // 创建编辑器
  quill = new Quill('#editor', {
    theme: 'snow',
    modules: {
      toolbar: toolbarOptions,
    },
  })
})
</script>

<template>
  <div>
    <!-- 表单 -->
    <el-form
      ref="formRef"
      :model="form"
      label-width="auto"
      :rules="formRules"
    >
      <!-- 标题 -->
      <el-form-item
        label="标题"
        prop="title"
        style="width: 400px"
      >
        <el-input
          v-model="form.title"
          placeholder="请输入标题"
        />
      </el-form-item>

      <!-- 频道 -->
      <el-form-item
        label="频道"
        style="width: 400px"
        prop="channel_id"
      >
        <el-select
          v-model="form.channel_id"
          placeholder="请选择频道"
        >
          <el-option
            v-for="item in channelList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          />
        </el-select>
      </el-form-item>

      <!-- 封面类型 -->
      <el-form-item label="封面">
        <el-radio-group v-model="form.cover_type">
          <el-radio :value="1">单图</el-radio>
          <el-radio :value="3">三图</el-radio>
          <el-radio :value="0">无图</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 图片上传 -->
      <el-form-item
        label=" "
        v-if="form.cover_type"
      >
        <el-upload
          v-model:file-list="files"
          :auto-upload="false"
          action="#"
          list-type="picture-card"
          :limit="form.cover_type"
          :on-preview="onPreview"
          :on-exceed="() => ElMessage.warning('已达到图片上传上限！')"
        >
          <el-icon> <Plus /> </el-icon>
        </el-upload>
      </el-form-item>

      <!-- 编辑器 -->
      <el-form-item label="内容">
        <div style="width: 100%">
          <div
            id="editor"
            style="min-height: 300px"
          />
        </div>
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item label=" ">
        <el-button @click="onSubmit('草稿')">存为草稿</el-button>
        <el-button
          @click="onSubmit('待审核')"
          type="primary"
          >发布文章</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 图片预览对话框 -->
    <el-dialog v-model="dialogVisible">
      <img
        style="width: 100%; height: 100%"
        w-full
        :src="dialogImageUrl"
        alt="Preview Image"
      />
    </el-dialog>
  </div>
  <!-- 预览图片 -->
</template>

<style scoped></style>
